/**
 * Created With IntelliJ IDEA
 * Description:leetcode: 2482. 行和列中一和零的差值
 * <a href="https://leetcode.cn/problems/difference-between-ones-and-zeros-in-row-and-column/">...</a>
 * User: DELL
 * Data: 2023-03-29
 * Time: 23:13
 */
public class Solution {
    /**
     * 总体思路就是先将每一列的1的个数减去0的个数存起来，
     * 后续遍历每一行，先遍历一行求出这一行的1的个数减去
     * 0的个数的值，然后初始化diff数组这一行即可
     *
     * 还有一种思路就是再创建一个数组，记录每一行的1的个数减去0的个数的值，
     * 之后直接初始化diff即可，本质上来说就是空间换取时间的操作
     */

    public int[][] onesMinusZeros(int[][] grid) {
        //题目中规定二维数组最少为一行一列的
        int row = grid.length;
        int col = grid[0].length;
        //先将每一列的1的个数减去0的个数存起来
        int[] colNum = new int[col];
        for (int j = 0; j < col; j++) {
            int temp = 0;
            for (int i = 0; i < row; i++) {
                //grid中只有1和0
                if (grid[i][j] == 1) {
                    temp++;
                } else {
                    temp--;
                }
            }
            colNum[j] = temp;
        }
        //初始化diff数组
        int[][] diff = new int[row][col];
        for (int i = 0; i < row; i++) {
            //先求出这一行1的个数减0的个数的值
            int temp = 0;
            for (int j = 0; j < col; j++) {
                if (grid[i][j] == 1) {
                    temp++;
                } else {
                    temp--;
                }
            }
            //初始化diff中的这一行
            for (int j = 0; j < col; j++) {
                diff[i][j] = temp + colNum[j];
            }
        }
        return diff;
    }
}